package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

@Component
public class MyTask {

    /**
     * 1,添加依赖
     * 2,在启动类上添加开启任务调度的注解@EnableScheduling
     * 3,编写定时任务类,编写定时任务方法,在方法上指定cron表达式
     * 定时任务,每隔5秒钟执行一次
     */
    /*@Scheduled(cron = "0/5 * * * * ?")
    public void task01(){
        System.out.println("定时任务开启了" + new Date());
    }*/

    @Autowired
    private OrderMapper orderMapper;

    /**
     * 处理支付超时订单
     * 要把超时的订单状态改成已取消
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void payForTimeoutOrderProcessing(){
        System.out.println("处理支付超时订单的任务执行了...");
        //1,计算当前时间-15分钟之后的时间
        LocalDateTime time = LocalDateTime.now().plusMinutes(-15);
        //2,获取订单表中所有超时未付款的数据集合
        List<Orders> ordersList =  orderMapper.getStasusByTime(Orders.PENDING_PAYMENT,time);
        //3,把这个集合遍历,得到每一个订单对象,然后再把每一个订单对象里面的状态改成已取消
        if(ordersList != null && ordersList.size() > 0){
            for (Orders orders : ordersList) {
                orders.setStatus(Orders.CANCELLED);
                orders.setCancelTime(LocalDateTime.now());
                orders.setCancelReason("支付超时,自动取消");
                orderMapper.update(orders);
            }
        }


    }

    /**
     * 处理派送中的订单状态
     * 要把超过1小时的的订单状态改成已完成
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void processTheStatusOfAnOrderInDelivery(){
        System.out.println("处理派送中订单的任务执行了...");
        LocalDateTime time = LocalDateTime.now().plusMinutes(-60);
        List<Orders> ordersList = orderMapper.getStasusByTime(Orders.DELIVERY_IN_PROGRESS, time);
        if(ordersList != null && ordersList.size() > 0){
            ordersList.forEach(orders -> {
                orders.setStatus(Orders.COMPLETED);
                orderMapper.update(orders);
            });
        }
    }


}
